package com.jn.erp.wechat.mp.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jn.erp.web.api.common.entity.InteractMessage;
import com.jn.erp.web.api.common.entity.dto.NoticeMessageDto;
import com.jn.erp.web.api.common.service.InteractMessageService;
import com.jn.erp.wechat.core.WxMessageData;
import com.jn.erp.wechat.mp.config.TmplmsgConfig;
import com.jn.erp.wechat.mp.handler.MpMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/11/28 14:36
 */
@Service
public class NoticeMessageService {


    @Autowired
    private TmplmsgConfig tmplmsgConfig;

    @Autowired
    private MpMessageHandler mpMessageHandler;

    @Autowired
    private InteractMessageService interactMessageService;

    public List<Long> arrearsMessage(String ids){
        List<Long> sendIds=new ArrayList<>();
        List<NoticeMessageDto> noticeMessageDtos = interactMessageService.renewalSendList(ids);
        if(noticeMessageDtos==null||noticeMessageDtos.size()==0){
            return null;
        }
        for (int i=0;i<noticeMessageDtos.size();i++){
            NoticeMessageDto noticeMessageDto=noticeMessageDtos.get(i);
            WxMessageData wxMessageData=new WxMessageData();
            wxMessageData.setOrgName(noticeMessageDto.getOrgName());
            wxMessageData.setCourseName(noticeMessageDto.getCourseName());
            wxMessageData.setStudentName(noticeMessageDto.getStudentName());
            wxMessageData.setRemainClass(noticeMessageDto.getRemainClass());
            if(StrUtil.isBlank(noticeMessageDto.getExpireDate())){
                //未设置，默认长期有效
                wxMessageData.setPeriodDate("2099-12-31");
            }else{
                wxMessageData.setPeriodDate(noticeMessageDto.getExpireDate());
            }
            wxMessageData.setOpenId(noticeMessageDto.getMpid());
            Boolean aBoolean = mpMessageHandler.ArrearsTextMessageUser(wxMessageData,tmplmsgConfig.getOverdueNotice());
            if(aBoolean){
                sendIds.add(noticeMessageDto.getInteractId());
            }
        }
        if(sendIds.size()>0){
            UpdateWrapper<InteractMessage> up=new UpdateWrapper();
            up.set("deleted", 1);
            up.in("id", sendIds);
            interactMessageService.update(up);
        }
        return sendIds;

    }
}
